package net.plankton.startup;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

public class Starter extends Thread {

	private String command;
	
	private boolean stuck=false;
	private boolean stopRunning=false;
	ServerSocket server;
	
	boolean withNetCheck=false;
	
	private String killall=null;
	
	private String controlFile=null;

	public Starter(String cmd) {
		command=cmd;
		this.controlFile=command.substring(command.lastIndexOf('/')+1);
//		new WriteOut().start();
	}
	public Starter(String cmd,String controlFile) {
		command=cmd;
//		new WriteOut().start();
		this.controlFile=controlFile;
	}
	
	public Starter(String cmd,String controlFile,String kilall) {
		command=cmd;
//		new WriteOut().start();
		this.controlFile=controlFile;
		this.killall=kilall;
		withNetCheck=true;
	}
	
	@Override
	public void run() {

		System.err.println("shutdown");
		Runtime rt = Runtime.getRuntime();
		int pid = 0;
		try {
			Process p=null;
			while (true) {
				int count=0;
				int errorCount=0;
				kill(rt, pid);
				p = rt.exec(command+" &");
				new WriteOut(p.getInputStream()).start();
				new WriteOut(p.getErrorStream()).start();
				System.err.println(new Date(System.currentTimeMillis()).toString());
				try {
					while (true) {
					Thread.sleep(100);
					count++;
						stopRunning=true;
//						new WatchDog(p).start();
//						p.exitValue();
						
						
					
						String cmd = "sh /video/checkRunning.sh "+controlFile;
//						System.err.println(cmd);
						
						Process watch = Runtime.getRuntime().exec(cmd);
						InputStream is = watch.getInputStream();
						
							
						BufferedReader bR = new BufferedReader(new InputStreamReader(is));
						String line = bR.readLine();
						int err=0;
						while (line!=null) {
							if (line.indexOf("grep")==-1 && line.indexOf("checkRunning.sh")==-1) {
								err++;
								while (line.indexOf(' ')==0)
									line=line.substring(1);
								pid = Integer.parseInt(line.substring(0,line.indexOf(' ')));
								stopRunning=false;
								
							}
							line = bR.readLine();
						}
						
						is.close();
						watch.destroy();
						if(err>1)
							kill(rt, pid);
						
						if (withNetCheck && !stopRunning && count>20) {
							stuck = true;
							WatchDog w = new WatchDog();
							w.start();
							Socket s = new Socket("127.0.0.1",6669);
							s.getOutputStream().write("ping\n".getBytes());
							s.getOutputStream().flush();
							s.close();
							Thread.sleep(1000);
							if (stuck)
								errorCount++;
							else
								errorCount=0;
							
							if (server!=null) {
								server.close();
							}
							if (errorCount>4)
								stopRunning=true;
						}
						if (stopRunning)
							break;
//						System.err.println(new Date(System.currentTimeMillis()).toString());
					}
				}
				catch (Exception e) {
					e.printStackTrace();
				}
				
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	private void kill(Runtime rt, int pid) throws IOException {
		if (pid>0) {
			System.err.println(pid);
			rt.exec("kill -9 "+pid);
		}
		if (killall!=null)
			rt.exec("killall "+killall);
	}
	
	class WriteOut extends Thread {
		
		private InputStream s;

		public WriteOut(InputStream s) {
			this.s=s;
		}

		@Override
		public void run() {

			try {
				BufferedReader reader = new BufferedReader(new InputStreamReader(s));
				String line = reader.readLine();
				while (line!=null)
				{
					System.err.println(line);
					line = reader.readLine();
				}


			}
			catch (Exception e) {
				e.printStackTrace();
			}
		}
		
	}
	
	class WatchDog extends Thread {
		

		public WatchDog(){
			
		}
		@Override
		public void run() {
			try {
				 server = new ServerSocket(6671);
				
				Socket s = server.accept();
				
				InputStream is = s.getInputStream();
				
				BufferedReader r = new BufferedReader(new InputStreamReader(is));
				String line = r.readLine();
				
				if (line.equals("ping")) {
					stuck=false;
					
				}
				else {
					System.err.println("restart!");
				}
				is.close();
				s.close();
				server.close();
				
			} catch (Exception e) {
				
				
			}
		}
	}
}
